//
//  MCgoodsListShowViewController.swift
//  StoreManage
//
//  Created by MC on 2018/8/31.
//  Copyright © 2018年 MC. All rights reserved.
//

import UIKit


class MCgoodsListShowViewController: MCViewController {
    
    private var pageNumber = 1
    
    private var selfCategoryId = 0 // 当前选中的分类Id
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        baseSetting()
        
        initUI()
        
        sendNetworking()
    }
    
    // MARK: - System Delegate
    
    // MARK: - Custom Delegate
    

    // MARK: - Setter & Getter
    private lazy var goodsListTableView: MCTableView = {
        let tableView = MCTableView.init(frame: CGRect.zero, style: UITableViewStyle.plain)
        tableView.backgroundColor = UIColor.white
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = UITableViewCellSeparatorStyle.none
        return tableView
    }()
    
    lazy var dataArrayM: NSMutableArray = {
        let arrayM = NSMutableArray.init()
        return arrayM
    }()
    
    private lazy var categoryTableView: MCTableView = {
        let tableView = MCTableView.init(frame: CGRect.zero, style: UITableViewStyle.plain)
        tableView.backgroundColor = UIColor.white
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = UITableViewCellSeparatorStyle.none
        return tableView
    }()
    
    lazy var categoryArrayM: NSMutableArray = {
        let arrayM = NSMutableArray.init()
        return arrayM
    }()

}


extension MCgoodsListShowViewController : UITableViewDelegate,UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        if tableView == categoryTableView {
            return categoryArrayM.count
        } else {
            return dataArrayM.count
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
       
        if tableView == categoryTableView {
            return 50
        } else {
            return 136
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        
        if tableView == categoryTableView {
            let cell = MCStoreGoodsLeftCell.init(style: UITableViewCellStyle.value1, reuseIdentifier: "cell")
            cell.model = categoryArrayM[indexPath.row] as! MCGoodsCategoryModel
            return cell

        } else {
            let cell = MCgoodsListShowCell.init(style: UITableViewCellStyle.value1, reuseIdentifier: "cell")
            cell.row = indexPath.row
            cell.selectionStyle = UITableViewCellSelectionStyle.none
            cell.model = self.dataArrayM[indexPath.row] as! MCGoodsListModel
            
            cell.closure = { row in
                let model = self.dataArrayM[row] as! MCGoodsListModel
                
                let vc = MCShareGoodsViewController()
                vc.goodsId = model.goodsId
                vc.goodsName = model.goodsName
                vc.lowestPrice = model.lowestPrice
                vc.suggestedPrice = model.suggestedPrice
                vc.gooodsImage = model.navigateImage
                
                MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)
                
            }
            
            return cell
        }
        
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if tableView == categoryTableView {
            var index = 0
            
            for model in self.categoryArrayM {
                
                (model as! MCGoodsCategoryModel).isChoose = false
                
                if index == indexPath.row {
                    (model as! MCGoodsCategoryModel).isChoose = true
                    selfCategoryId = (model as! MCGoodsCategoryModel).selfCategoryId.intValue
                }
                index += 1
            }
            pageNumber = 1
            categoryTableView.reloadData()
            self.sendNetworking_goodsListWithCategoryId(self.selfCategoryId)
        } else {
            let model = self.dataArrayM[indexPath.row] as! MCGoodsListModel
            let vc = MCGoodsDetailViewController()
            vc.isOnShelves = 1000
            vc.goodsId = model.goodsId
            MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)
        }
    }
}


//MARK: 通知回调，闭包回调，点击事件
extension MCgoodsListShowViewController {
    @objc func rightItemClicked() {
        let vc = MCgoodsListShowSearchViewController()
        MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)
    }
}


//MARK: 网络请求
extension MCgoodsListShowViewController {

    func sendNetworking() {
        sendNetworking_cagetory()
    }
    
    func sendNetworking_cagetory() {
        MCNetwork.POST(JAVA_querySelfCategoryPage, success: { (data) in
            let dataArray = data.arrayObject ?? []
            
            var index = 0
            
            for dict in dataArray {
                let model = MCGoodsCategoryModel()
                model.setValuesForKeys(dict as? [String:Any] ?? [:])
                
                if index == 0 {
                    self.selfCategoryId = model.selfCategoryId.intValue
                    model.isChoose = true
                }
                self.categoryArrayM.add(model)
                index += 1
            }
            self.categoryTableView.reloadData()
            self.sendNetworking_goodsListWithCategoryId(self.selfCategoryId)
        })
    }

    
    func sendNetworking_goodsListWithCategoryId(_ id:Int) {
        
        let para = [
            "pageNum"        : pageNumber,
            "selfCategoryId" : id,
            "type"           : 1
            ] as [String : Any]
        
//        MCHUD_default(message: "加载中...", view: view, delay: 0)
        
        MCNetwork.POST(JAVA_queryGoodsBySelfCategoryId, para, vc: self, success: { (data) in
            
//            MCHUD_hidden(view: self.view)
            
            self.goodsListTableView.mj_header.endRefreshing()
            self.goodsListTableView.mj_footer.endRefreshing()
            
            if self.pageNumber == 1 {
                self.dataArrayM.removeAllObjects()
                self.goodsListTableView.mj_footer.resetNoMoreData()
            }
            
            let dataArray = data.arrayObject ?? []
            
            
            if dataArray.count == 0 {
                self.goodsListTableView.mj_footer.endRefreshingWithNoMoreData()
            }

            if dataArray.count + self.dataArrayM.count == 0 {
                self.goodsListTableView.showBgImage()
            } else {
                self.goodsListTableView.hideBgImage()
                
                for dict in dataArray {
                    let model = MCGoodsListModel()
                    model.setValuesForKeys(dict as! [String : Any])
                    self.dataArrayM.add(model)
                }
            }
            self.goodsListTableView.reloadData()
        }, failure: nil)
    }
    
}

//MARK: UI的处理,通知的接收
extension MCgoodsListShowViewController {
    func baseSetting() {
        self.title = "商品分享"
        view.backgroundColor = UIColor.MCGray_light
        
        self.goodsListTableView.mj_header = MCRefreshHeader.init(refreshingBlock: {
            self.pageNumber = 1
            self.sendNetworking_goodsListWithCategoryId(self.selfCategoryId)
        })
        
        self.goodsListTableView.mj_footer = MCRefreshFooter.init(refreshingBlock: {
            self.pageNumber += 1
            self.sendNetworking_goodsListWithCategoryId(self.selfCategoryId)
        })
        
        
        navigationItem.rightBarButtonItem = MCSetBarButtonItem_image(#imageLiteral(resourceName: "Reuse_search"), target: self, selector: #selector(rightItemClicked))
    }
    
    func initUI() {
        
        view.addSubview(categoryTableView)
        categoryTableView.snp.remakeConstraints { (make) ->Void in
            make.left.top.equalTo(view)
            make.width.equalTo(MCAdaptationModel(100))
            make.bottom.equalTo(view).offset(-MCSafeAreaBottomHeight)
        }
        
        view.addSubview(goodsListTableView)
        goodsListTableView.snp.remakeConstraints { (make) ->Void in
            make.left.equalTo(categoryTableView.snp.right).offset(5)
            make.right.equalTo(view)
            make.top.equalTo(view).offset(5)
            make.bottom.equalTo(view).offset(-MCSafeAreaBottomHeight)
        }
    }
}


